package com.ws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pojo.ChatBean;
import com.pojo.Jiedairen;
import com.service.JiedairenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author:liao
 * @Discription:websocket服务
 */
@ServerEndpoint("/websocket/{name}/{usertype}/{uname}")
@Component
public class WebSocketServer {

//    @Autowired
//    private HttpServletRequest request;

    //存储客户端的用户连接对象,每个用户的客户端连接都会产生一个连接对象
    private static ConcurrentHashMap<String, WebSocketServer> map = new ConcurrentHashMap();

    //存储客户端的客服连接对象,每个客服的客户端连接都会产生一个连接对象
    public static ConcurrentHashMap<String, WebSocketServer> kefumap = new ConcurrentHashMap();
    //定义一个map用来存储客服的聊天数量（人数）
    public static Map<String, Integer> chatmap = new HashMap<String, Integer>();
    //定义一个map建立用户正在聊天的客服名：key为用户名，value为客服名，因为key不能重复
    private static Map<String, String> kefuAndUser = new HashMap<>();
    //每个连接都会有自己的会话  //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private String name;
    /**
     * 建立websocket连接
     * @param name userid 一般是手机号 例如：+86133****0750
     * @param usertype user1表示用户连接 user2表示客服连接
     * @param uname 用户名，注册时的名字
     * @param session
     * @throws IOException
     */
    @OnOpen
    public void open(Session session,@PathParam("name") String name,@PathParam("usertype") String usertype,@PathParam("uname") String uname) throws IOException {
        String kefuname = ""; //为用户匹配的客服名
        if (usertype.equals("user2")) {    // 如果是客服链接
            kefumap.put(name, this);
            this.session = session;
            this.name = name;
            chatmap.put(name, 0);
        }else  if (usertype.equals("user1")) { // 如果是游客链接了
            map.put(name, this);
            this.session = session;
            this.name = name;
            if(chatmap.size()>0){   // 如果有客服在线
                int minkefu = 0;      //为用户匹配客服，找到聊天数量最少的那个客服，
                int abc = 0;
                Set<Map.Entry<String, Integer>> enchat = chatmap.entrySet();   // 所有的客服
                for (Map.Entry<String, Integer> entry : enchat) {
                    int ab = entry.getValue();
                    if (abc == 0) {
                        kefuname = entry.getKey();
                        minkefu = ab;
                    }
                    abc = 1;
                    if (ab <= minkefu) {
                        kefuname = entry.getKey();
                        minkefu = ab;
                    }
                }
                JSONObject yonghujson = new JSONObject();
                JSONObject kefujson = new JSONObject();//kefujson是发送给客服的消息内容：type=1表示客服要增加一个选项卡，type=2才是聊天时发的消息，message是具体的发送内容 type==3表示没有用户已下线
                kefuAndUser.put(name, kefuname);
                chatmap.put(kefuname,minkefu+1);
                String kefujs = "{\"type\":1,\"to\":\"" + name + "\",\"from\":\"" + kefuname + "\",\"msg\":" + kefujson + "}";
                getMessage(kefujs);//给客服发消息
                String yonghujs = "{\"type\":1,\"to\":\"" + name + "\",\"from\":\"" + kefuname + "\",\"msg\":" + yonghujson + "}";
                this.send(yonghujs);    // 给游客发消息
            }else{  // 没有客服在线
                Set<Map.Entry<String, WebSocketServer>> youkes = map.entrySet();    //用户的连接
                String msg = "{\"type\":3,\"to\":\"" + name + "\",\"from\":\"" + kefuname +  "\"}";;
                this.send(msg);
            }
        }
    }

    @OnClose
    public void close() throws IOException {
        try {
            if(name.startsWith("youke")){   // 如果是游客离开了
                String kefu= kefuAndUser.get(name);
                Set<Map.Entry<String, WebSocketServer>> kefus = kefumap.entrySet();  //客服的连接
                String msg = "{\"type\":3,\"to\":\"" + kefu + "\",\"from\":\"" + name +  "\"}";;
                for (Map.Entry<String, WebSocketServer> entry : kefus) {
                    if(entry.getKey().equals(kefu))     // 找到该游客对应的客服
                    {
                        kefuAndUser.remove(name);
                        map.remove(name);
                        entry.getValue().send(msg);
                    }
                }
            }else{              // 如果是客服离开了
                kefumap.remove(name);
                chatmap.remove(name);
                Set<Map.Entry<String, WebSocketServer>> youkes = map.entrySet();    //用户的连接
                for (Map.Entry<String, String> kefuheyouke : kefuAndUser.entrySet()) {
                    if(kefuheyouke.getValue().equals(name)){
                        for (Map.Entry<String, WebSocketServer> entry : youkes) {
                            if (kefuheyouke.getKey().equals(entry.getKey())) {
                                String msg = "{\"type\":4,\"to\":\"" + name + "\",\"from\":\"" + entry.getKey() +  "\"}";;
                                entry.getValue().send(msg);         // 给用户发信息提示
                            }
                        }
                    }
            }
        }
        }catch (Exception e){
            System.out.println(e);
        }

    }

    @OnError
    public void error(Throwable error) {
        error.printStackTrace();
    }

    @OnMessage
    public void getMessage(String message) throws IOException {
        Set<Map.Entry<String, WebSocketServer>> youkes = map.entrySet();    //用户的连接
        Set<Map.Entry<String, WebSocketServer>> kefus = kefumap.entrySet();  //客服的连接
        if(this.name.startsWith("youke")){    // 如果是游客发的消息,就转发给客服
            String kefu= kefuAndUser.get(name);
            for (Map.Entry<String, WebSocketServer> entry : kefus) {
                if(entry.getKey().equals(kefu))     // 找到该游客对应的客服
                {
                    entry.getValue().send(message);
                }
            }
        } else{        // 如果是客服发的消息,就转发给游客
            ChatBean bean = JSON.parseObject(message,ChatBean.class);
            for (Map.Entry<String, WebSocketServer> entry : youkes) {
                if(entry.getKey().equals(bean.getTo())) {
                    entry.getValue().send(message);
                }
            }
        }
    }

    public void send(String message) throws IOException {
        if (session.isOpen()) {
            session.getBasicRemote().sendText(message);
        }
    }

}

